package com.example.yiqinmanagersystem.httpapi;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.yiqinmanagersystem.entity.ChinaToal;
import com.example.yiqinmanagersystem.entity.NocvData;
import com.example.yiqinmanagersystem.service.ChinaTotalService;
import com.example.yiqinmanagersystem.service.DataDisplayService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.SimpleFormatter;

/*
 **@Author:youpeng
 **Created on 2022/9/13
 */
@Component
public class ChinaTotalScheduleTask {

    @Resource
    private ChinaTotalService chinaTotalService;

    @Resource
    private DataDisplayService dataDisplayService;

    @Resource
    private RedisTemplate redisTemplate;

    /*
    * 获取实时数据并渲染（确诊，疑似，死亡，输入）
    * 每小时更新一次
    * */
    @Scheduled(fixedDelay = 30000)
//    @Scheduled(cron = "0 0 8,9,10,11,12,16,18,20 * * ?")
    public  void updateChinaTotalToDB() throws Exception{
        HttpUtils httpUtils = new HttpUtils();
        String string = httpUtils.getData();
        //1.所有的数据含msg, code, data...
        JSONObject jsonObject = JSONObject.parseObject(string);
        Object data = jsonObject.get("data");
//        System.out.println(data);
        //2.data
        JSONObject jsonObjectData = JSONObject.parseObject(data.toString());
        Object chinaTotalData = jsonObjectData.get("chinaTotal");
        Object overseaLastUpdateTime = jsonObjectData.get("overseaLastUpdateTime");
//        System.out.println(overseaLastUpdateTime);
//        System.out.println(chinaTotalData);
        //3.获取 total 全国疫情数据
        JSONObject jsonObjectTotal = JSONObject.parseObject(chinaTotalData.toString());
        Object totalData = jsonObjectTotal.get("total");
//        System.out.println(totalData);
        //4.全国数据total
        JSONObject object = JSONObject.parseObject(totalData.toString());
        Object confirm = object.get("confirm");
        Object input = object.get("input");
        Object severe = object.get("severe");
        Object heal = object.get("heal");
        Object dead = object.get("dead");
        Object suspect = object.get("suspect");
        //5.为实体赋值
        ChinaToal dataEntity = new ChinaToal();
        dataEntity.setId(1);
        dataEntity.setConfirm((Integer) confirm);
        dataEntity.setInput((Integer) input);
        dataEntity.setSevere((Integer) severe);
        dataEntity.setHeal((Integer) heal);
        dataEntity.setDead((Integer) dead);
        dataEntity.setSuspect((Integer) suspect);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dataEntity.setUpdateTime(format.parse(String.valueOf(overseaLastUpdateTime)));
//        System.out.println(dataEntity);
        //6.插入数据库（更新）
//        chinaTotalService.save(dataEntity);
        chinaTotalService.saveOrUpdate(dataEntity);

//        System.out.println("插入（修改）成功");

        /*
        * 获取中国各个省份的数据并实现自动刷新
        * */
        //1.拿到 areaTree
        JSONArray areaTree = jsonObjectData.getJSONArray("areaTree");
        Object[] objects = areaTree.toArray();
        //遍历所有国家
        /*for (int i = 0; i < objects.length; i++) {
            JSONObject object1 = JSONObject.parseObject(objects[i].toString());
            Object name = object1.get("name");
            System.out.println(name);
        }*/
        //拿到中国的数据
        JSONObject jsonObject1 = JSONObject.parseObject(objects[2].toString());
        JSONArray children = jsonObject1.getJSONArray("children");
        Object[] objects1 = children.toArray(); //各个省份

        //实体数据集合
        List<NocvData> list = new ArrayList<>();
        for (int i = 0; i < objects1.length; i++) {
            JSONObject jsonObject2 = JSONObject.parseObject(objects1[i].toString());
            Object name = jsonObject2.get("name"); //省份名称
            Object timePro = jsonObject2.get("lastUpdateTime"); //省份更新时间
            Object total = jsonObject2.get("total");
            JSONObject jsonObject3 = JSONObject.parseObject(total.toString());
            Object confirmData = jsonObject3.get("confirm"); //L累计确诊人数
            Object healData = jsonObject3.get("heal"); //L累计确诊人数
            Object deadData = jsonObject3.get("dead"); //L累计确诊人数
            int confirm1 = (Integer) confirmData-(Integer) healData-(Integer) deadData;
//            System.out.println(("省份-》" + name + ": " + confirm1 + "人"));
            NocvData nocvData = new NocvData();
            nocvData.setName((String) name);
            nocvData.setValue((Integer) confirm1);
            if(timePro==null){
                nocvData.setUpdateTime(new Date());
            }else {
                nocvData.setUpdateTime(format.parse(String.valueOf(timePro)));
            }
            //创建条件
            UpdateWrapper<NocvData> demo = new UpdateWrapper<NocvData>()
                    .eq(!(nocvData.getName()==null),"name",nocvData.getName());
            dataDisplayService.update(nocvData,demo);
            list.add(nocvData);
        }

        //第一次全部数据插入（更析）数据库
//        dataDisplayService.saveOrUpdateBatch(list);

        //7.删除缓存redis 缓存
        if(redisTemplate!=null){
            redisTemplate.delete("chinaTotal");
            redisTemplate.delete("chinaData");
        }
    }

}
